import React, { useState, useEffect } from "react";
import { Provider } from 'react-redux';
import store from './store';
import { HashRouter } from "react-router-dom";
import { renderRoutes } from 'react-router-config';
import routes from './router';
import Cookies from 'js-cookie';
import intl from 'react-intl-universal';

const locales = {
	'en-US': require('./locales/en-US.json'),
	'zh-CN': require('./locales/zh-CN.json'),
	'zh-TW': require('./locales/zh-TW.json'),
	'ko-KR': require('./locales/ko-KR.json'),
	'ru-RU': require('./locales/ru-RU.json'),
	'th-TH': require('./locales/th-TH.json'),
	'vi-VN': require('./locales/vi-VN.json'),
};
//通过cookie换成本地语言包
let cookieLangChange = str => {
	switch (str) {
		case "cn":
			return 'zh-CN';
		case "tw":
			return 'zh-TW'; //繁体
		case "kr":
			return 'ko-KR'; //韩语
		case "en":
			return 'en-US';
		case "ru":
			return 'ru-RU'; //俄语
		case "th":
			return 'th-TH'; //泰语
		case "vn":
			return 'vi-VN'; //越南  
		default:
			return 'en-US';
	}
};
function App() {
	//主题
	const changeTheme = () => {
		// 主要通过切换body的class来切换css变量 
		let body = document.getElementsByTagName('body')[0];
		Cookies.get('theme') ? body.className = Cookies.get('theme') : body.className = 'dark-theme';
	}
	const customConfirm = (message, callback) => { }
	const loadLocales = (lang) => {
		intl.init({ currentLocale: lang ? lang : getLanguage(), locales, }).then(() => {
			// 回调
		});
	}
	const getLanguage = () => {
		const chooseLanguage = cookieLangChange(Cookies.get('lang'));
		if (chooseLanguage) return chooseLanguage;
		const language = (navigator.language || navigator.browserLanguage).toLowerCase();
		const localeArr = Object.keys(locales);
		for (const locale of localeArr) {
			if (language.indexOf(locale) > -1) {
				return locale
			}
		}
		return 'zh-CN'
	}
	useEffect(() => {
		changeTheme();//获取主题
		loadLocales();// 设置初始语言
	}, []);
	return (
		<Provider store={store}>
			<HashRouter getUserConfirmation={customConfirm}>
				{renderRoutes(routes)}
			</HashRouter>
		</Provider> 
	)
}

export default App;
